#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/11/19 14:59
# @Author  : huidong.bai
# @File    : midea_control_api.py
# @Software: PyCharm

import base64
import hashlib
import requests
import json
import uuid


body = {
    'client_id': 'orion.ovs.client.1507867446289',
    'query': '',
    'sid': '',
    'sn': ''
}


# md5加密
def md5value(key):
    input_name = hashlib.md5()
    input_name.update(key.encode("utf-8"))
    return (input_name.hexdigest()).lower()


# 拼接参数
def body_handle():
    first_str = ''
    for key, value in body.items():
        tmp = key + '=' + value + '&'
        first_str += tmp
    return first_str


# 获取签名
def get_sign(client_secret):
    first_str = body_handle()
    first_str += f'client_secret={client_secret}'
    bytes_str = first_str.encode("utf-8")
    str_url = base64.b64encode(bytes_str)
    pre_str = bytes.decode(str_url)
    sign = md5value(pre_str)
    return sign


# 构造body
def get_body(query, sn, client_id, client_secret):
    sid = str(uuid.uuid1()).replace('-', '')
    if body.__contains__('sign'):
        del body['sign']
    body['sn'] = sn
    body['query'] = query
    body['client_id'] = client_id
    body['sid'] = sid
    sign = get_sign(client_secret)
    body['sign'] = sign
    return body


# 执行自定义指令
def execute(query, params):
    headers = {'Content-Type': 'application/json'}
    body_str = get_body(query=query,
                        sn=params.get('sn'),
                        client_id=params.get('osClientId'),
                        client_secret=params.get('product_secret'))
    re_body = json.dumps(body_str)
    response = requests.request("POST", params.get('url'), headers=headers, data=re_body)
    print(re_body)
    return response.text


if __name__ == '__main__':
    data = {
        'sn': '111000010213019416Z072',
        'url': 'http://skillpub-xy.ainirobot.com/extapi/inverseControl',
        'product_secret': 'B9AEB5A7BAD0C6A6EEB8C2304772A943',
        'osClientId': 'orion.ovs.client.1507867446289',
        'productId': '',
        'speakerVersion': '1.5.3',
        'romVersion': '1.5.3',
    }

    execute('播放挪威的森林', data)
